package com.example.api.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Service
public class AccountService {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 从用户账户中借出
     */
    public void debit(String userId, int money) {
        String url = "http://127.0.0.1:18084/account";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();

        map.add("userId", userId);
        map.add("money", money + "");

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(
                map, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(url, request,
                String.class);
    }

    public String get(String commodityCode, int count) {
        return restTemplate.getForObject("http://storage/echo/" + commodityCode + "/" + count, String.class);
    }
}
